<template>
  <div class="playBack-page">
    <div class="left">
      <div class="title">
        <span>设备列表</span>
        <el-select v-model="provinceCode" :loading="$loadingPlugin.getProvinceList" filterable clearable size="mini" popper-class="select-popper" placeholder="全部省份" style="width: 80px;" @change="provinceChange">
          <el-option v-for="item in provinceList" :key="item.id" :value="item.orgSN" :label="item.name" />
        </el-select>
      </div>
      <div class="content">
        <div class="org">
          <devece-tree
            ref="deveceTreeRef"
            title="无"
            :tree-data="treeData"
            :loading="$loadingPlugin.getTreeData"
            @currentChange="currentChange"
            @refresh="getTreeData"
          />
        </div>
      </div>
    </div>
    <div class="right">
      <el-table-form class="search-form" :model="form">
        <el-form-item label="回放开始时间：" :table-form-merge="1.5">
          <el-date-picker
            v-model="form.value1"
            value-format="yyyy-MM-dd"
            class="bac"
            popper-class="date-panel"
            type="date"
            :picker-options="pickerOptions"
            placeholder="选择日期"
            @change="changeTime"
          />
        </el-form-item>
        <el-form-item>
          <el-time-select
            v-model="form.value2"
            class="bac"
            :picker-options="{
              start: '00:00',
              step: '01:00',
              end: endTime
            }"
            placeholder="选择时间"
            popper-class="time-panel"
          />
        </el-form-item>
        <template #btns>
          <el-button class="search-btn" @click="searchBack">查询</el-button>
        </template>
      </el-table-form>
      <div class="video-container1">
        <div class="title">
          {{ playBackInfo.corpName }}
        </div>
        <div v-show="!playBackInfo.videoUrl" class="video" style="cursor: pointer;" @click="resetVideo">
          <div v-if="tagInfo === '回放内容为开始时间后一小时内的视频'">{{ tagInfo }}</div>
          <div v-else>{{ tagInfo }}, 请点击<span class="hover">重试</span></div>
        </div>
        <div v-show="playBackInfo.videoUrl" class="video">
          <EasyPlayer
            :video-url="playBackInfo.videoUrl"
            :speed="false"
            :loading="playBackInfo.isLoading"
            controls
            fluent
            stretch
            autoplay
            muted
            @message="message"
            @timeupdate="timeupdate"
            @ended="ended"
          />
        </div>
      </div>
      <div class="time-container">
        <time-rule v-if="timePoint.length" ref="timeRuleRef" :time="timePoint" @getTimeValue="getTimeValue" />
      </div>
    </div>
  </div>
</template>

<script>
  import dayjs from 'dayjs'
  //   import { corpAllList, queryDeviceList, organizationQueryList } from '@/api'
  //   import getTreeData from '@/utils/jsonTree'
  //   import { setDeviceChildren } from '@/utils'
  import EasyPlayer from '@easydarwin/easyplayer'
  import axios from 'axios'

  export default {
    name: 'playBack',
    components: {
      timeRule: require('@/components/timeRule').default,
      deveceTree: require('./deviceTree.vue').default,
      EasyPlayer
    },
    data() {
      return {
        isReloadVideo: false,
        delayTime: null,
        tagInfo: '回放内容为开始时间后一小时内的视频',
        provinceCode: '',
        provinceList: [],
        index: 0,
        search: '',
        timePoint: [],
        treeData: [],
        playBackInfo: {
          corpName: '--',
          videoUrl: '',
          isLoading: false
        },
        currentDevice: null,
        form: {
          value1: dayjs(new Date()).format('YYYY-MM-DD'),
          value2: dayjs(new Date()).format('HH') - 1 + ':00'
        },
        pickerOptions: {
          disabledDate: time => {
            if (time.getTime() > Date.now()) {
              return true
            }
            const sdate = new Date()
            const day = 90
            sdate.setTime(sdate.getTime() - 3600 * 1000 * 24 * day)
            if (time.getTime() < sdate.getTime()) {
              return true
            }
            return false
          }
        }
      }
    },
    computed: {
      endTime() {
        if (dayjs(this.form.value1).format('YYYYMMDD') === dayjs(new Date()).format('YYYYMMDD')) {
          return dayjs(new Date()).format('HH') + ':00'
        } else {
          return '24:00'
        }
      }
    },
    created() {
    //   this.getProvinceList()
    //   this.getTreeData()
    },

    methods: {
      ended() {
        this.isReloadVideo = true
        document.querySelector('.vjs-control-bar').style.display = 'none'
      },
      useDelay() {
        if (this.delayTime) {
          clearInterval(this.delayTime)
        }
        this.delayTime = setInterval(() => {
          if (this.getId('video') && this.getId('video').src) {
            const buffered1 = this.getId('video').buffered
            if (buffered1.length > 0) {
              // 缓冲区末尾时间
              const end = buffered1.end(0)
              // diff是缓冲区末尾时间和当前播放时间的差值
              const diff = end - this.getId('video').currentTime
              // 如果差值大于1，说明延迟大于1s，需要手动跳帧
              if (diff > 1) {
                // 将当前播放时间设置为缓冲区末尾时间减一的这个时间点
                this.getId('video').currentTime = end - 1
              }
            }
          }
        }, 20000)
      },
      getId(id) {
        return document.querySelector(id)
      },
      resetVideo() {
        this.playBackInfo.videoUrl = ''
        setTimeout(() => {
          this.searchBack()
        }, 100)
      },
      timeupdate(time) {
        if (time) this.playBackInfo.isLoading = false
      },
      message(err) {
        if (err.type === 'error') {
          this.playBackInfo.videoUrl = undefined
          this.tagInfo = err.message || '当前时间段无回放视频'
        }
      },
      async getProvinceList() {
        // const res = await organizationQueryList({
        //   orgType: 2,
        //   useStatus: 0 // -1查询所有，0查询已启用
        // })
        // this.provinceList = res.data
      },
      changeTime() {
        this.form.value2 = undefined
      },
      // 选中设备
      currentChange(val) {
        if (!val.isVideo) return
        if (!val.isOnline) return this.$message.error('当前设备不在线')
        this.currentDevice = val
      },
      // 获取机构树
      async getTreeData(orgSN) {
        // const [res, res1] = await Promise.all([corpAllList({ orgSN: orgSN || '' }), queryDeviceList({ currentPage: 1, pageSize: 99999 })])
        // const data = res.data.map(item => ({
        //   label: item.name,
        //   id: item.id,
        //   ...item
        // }))
        // // 对返回的res1数据进行处理 orgId deveceName isVideo isOnline url
        // const newData = setDeviceChildren(data, res1.data.rows.map(item => {
        //   return {
        //     ...item,
        //     isVideo: item.deviceNo,
        //     isOnline: item.deviceStatus,
        //     url: item.liveAddress.replace('live', 'rcd').slice(0, -8)
        //   }
        // }))
        // this.treeData = getTreeData(newData, 'parentId', 'id')
      },
      // 点击查询回放视频
      searchBack() {
        if (!this.form.value1 || !this.form.value2) return this.$message.error('请选择回放开始时间')
        if (!this.currentDevice) return this.$message.error('请选择设备')
        this.useDelay()
        this.playBackInfo.corpName = this.currentDevice.allName
        this.timePoint = [this.form.value2]
        const arr = this.form.value2.split(':')
        arr[0].length === 2 ? '' : arr[0] = '0' + arr[0]
        this.playBackInfo.videoUrl = this.currentDevice.url + '_' + dayjs(this.form.value1).format('YYYYMMDD') + arr[0] + '0000.flv'
        this.playBackInfo.isLoading = true
        if (this.index !== 0) {
          this.$refs.timeRuleRef.resetLine()
        }
        this.index++
      },
      // 拖动时间轴播放视频
      getTimeValue(val) {
        this.useDelay()
        const arr = val.split(':')
        const url = this.currentDevice.pointAddress.split('/')[2]
        const key = this.currentDevice.pointAddress.split('/')[5].split('&')[2].split('=')[1]
        if (this.isReloadVideo) {
          this.playBackInfo.videoUrl = ''
          setTimeout(() => {
            const arr = this.form.value2.split(':')
            arr[0].length === 2 ? '' : arr[0] = '0' + arr[0]
            this.playBackInfo.videoUrl = this.currentDevice.url + '_' + dayjs(this.form.value1).format('YYYYMMDD') + arr[0] + '0000.flv'
            this.playBackInfo.isLoading = true
            this.isReloadVideo = false
            this.tagInfo = ''
          }, 500)
          setTimeout(() => {
            axios.get(`http://${url}/index/api/VodOperate?PubName=rcd&CamCode=${this.currentDevice.deviceNo}_0&StartTime=${dayjs(this.form.value1).format('YYYYMMDD')}${arr[0]}0000&SeekSeconds=${Number(arr[1] * 60)}&secret=${key}`)
          }, 1000)
        } else {
          axios.get(`http://${url}/index/api/VodOperate?PubName=rcd&CamCode=${this.currentDevice.deviceNo}_0&StartTime=${dayjs(this.form.value1).format('YYYYMMDD')}${arr[0]}0000&SeekSeconds=${Number(arr[1] * 60)}&secret=${key}`)
          this.playBackInfo.isLoading = true
        }
      },
      async provinceChange(value) {
        await this.getTreeData(value)
        this.currentDevice = null
        this.$refs.deveceTreeRef.$refs.tree.setCurrentKey(null)
      }
    }
  }
</script>

<style lang="scss" scoped>
.hover {
  color: #1976D2;
  &:hover {
    color: aqua;
  }
}
.time-container {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 75px;
  min-width: 1220px;
  background-color: #fff;
  border: 1px solid #DCDFE6;
  border-radius: 0 0 6px 6px;
}
.bac {
  /deep/ .el-input__inner {
    // background-color: #111a2d !important;
    border: none !important;
  }
}
.playBack-page {
  display: flex;
  height: calc(100vh - 150px);
  padding: 16px;
  padding: 10px 10px 0 10px;
  margin: 6px 8px;
  cursor: pointer;
  .left {
    width: 260px;
    margin-right: 16px;
    font-size: 14px;
    background: #fff;
    border: 1px solid #DCDFE6;
    border-radius: 6px;
    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 40px;
      padding: 8px;
      background: #fff;
      border-bottom: 1px solid #DCDFE6;
      border-radius: 6px 6px 0 0;
      /deep/ .el-select .el-input__inner {
        padding: 0;
        background-color: transparent;
        border-color: transparent;
      }
    }
    .content {
      height: calc(100% - 40px);
      padding: 8px;
      .search {
        /deep/ .el-input__inner {
          background-color: #fff;
          border-color: transparent;
          border-radius: 50px;
        }
      }
      .org {
        height: calc(100% - 40px);
        margin-top: 12px;
        /deep/ .el-tree {
          background-color: transparent;
        }
      }
    }
  }
  .right {
    width: calc(100% - 276px);
    height: 100%;
    overflow-x: auto;
    .video-container1 {
      width: 100%;
      //height: 730px;
      height: calc(100% - 126px);
      min-width: 1220px;
      .title {
        height: 40px;
        padding: 0 16px;
        line-height: 40px;
        background: #fff;
        border: 1px solid #DCDFE6;
        border-radius: 6px 6px 0 0;
      }
      .video {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: calc(100% - 40px);
        font-size: 18px;
        background-color: #000;
        user-select: none;
      }
    }
  }
}
</style>
